
import turtle
import random
points = [[0, 0], [0, -20], [0, -40]]
# 0向上  1向下  2向左 3向右
direction = 0
r=random.randint(-300,300)
b=random.randint(-300,300)
food = [r, b]
def snake():
    turtle.clear()
    for i in range(len(points)):
        turtle.up()
        turtle.goto(points[i])
        turtle.down()
        turtle.dot(20, 'red')
    point = points[0].copy()
    turtle.up()
    turtle.goto(food)
    turtle.down()
    turtle.dot(20, 'green')
    is_delete = True
    if abs((point[0])-food[0]) < 20 and abs((point[1])-food[1]) < 20:
        food[0] = random.randint(-300, 300)
        food[1] = random.randint(-300, 300)
        is_delete = False
    if direction == 0:
        point[1] += 20
    elif direction == 1:
        point[1] -= 20
    elif direction == 2:
        point[0] -= 20
    elif direction == 3:
        point[0] += 20
    points.insert(0, point)
    if is_delete:
        points.pop()

    turtle.ontimer(snake, 500)

def up():
    global direction
    direction=0
def down():
    global direction
    direction=1
def left():
    global direction
    direction=2
def right():
    global direction
    direction=3







turtle.tracer(False)
snake()
turtle.onkeypress(up,'Up')
turtle.onkeypress(down,'Down')
turtle.onkeypress(left,'Left')
turtle.onkeypress(right,'Right')
turtle.listen()
turtle.done()

